package com.dkd.manage.service.impl;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.dkd.common.constant.DkdContants;
import com.dkd.common.exception.ServiceException;
import com.dkd.common.utils.DateUtils;
import com.dkd.manage.domain.Emp;
import com.dkd.manage.domain.TaskDetails;
import com.dkd.manage.domain.VendingMachine;
import com.dkd.manage.domain.dto.TaskDetailsDto;
import com.dkd.manage.domain.dto.TaskDto;
import com.dkd.manage.domain.vo.TaskVo;
import com.dkd.manage.service.IEmpService;
import com.dkd.manage.service.ITaskDetailsService;
import com.dkd.manage.service.IVendingMachineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.dkd.manage.mapper.TaskMapper;
import com.dkd.manage.domain.Task;
import com.dkd.manage.service.ITaskService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工单Service业务层处理
 *
 * @author ITfuck
 * @date 2025-02-19
 */
@Service
public class TaskServiceImpl implements ITaskService {
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private IVendingMachineService vendingMachineService;

    @Autowired
    private IEmpService empService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ITaskDetailsService taskDetailsService;
    /**
     * 查询工单
     *
     * @param taskId 工单主键
     * @return 工单
     */
    @Override
    public Task selectTaskByTaskId(Long taskId) {
        return taskMapper.selectTaskByTaskId(taskId);
    }

    /**
     * 查询工单列表
     *
     * @param task 工单
     * @return 工单
     */
    @Override
    public List<Task> selectTaskList(Task task) {
        return taskMapper.selectTaskList(task);
    }

    /**
     * 新增工单
     *
     * @param task 工单
     * @return 结果
     */
    @Override
    public int insertTask(Task task) {
        task.setCreateTime(DateUtils.getNowDate());
        return taskMapper.insertTask(task);
    }

    /**
     * 修改工单
     *
     * @param task 工单
     * @return 结果
     */
    @Override
    public int updateTask(Task task) {
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.updateTask(task);
    }

    /**
     * 批量删除工单
     *
     * @param taskIds 需要删除的工单主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskIds(Long[] taskIds) {
        return taskMapper.deleteTaskByTaskIds(taskIds);
    }

    /**
     * 删除工单信息
     *
     * @param taskId 工单主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskId(Long taskId) {
        return taskMapper.deleteTaskByTaskId(taskId);
    }

    /**
     * 根据工单列表
     *
     * @param task
     * @return
     */
    @Override
    public List<TaskVo> selectTaskVoListByTaskId(Task task) {
        return taskMapper.selectTaskVoListByTaskId(task);
    }

    /**
     * 新增运营，运维工单
     *
     * @param taskDto
     * @return
     */
    @Transactional
    @Override
    public int insertTaskDto(TaskDto taskDto) {
        // 判断设备是否存在
        VendingMachine vendingMachine = vendingMachineService.selectVendingMachineByInnerCode(taskDto.getInnerCode());
        if (vendingMachine == null) {
            throw new ServiceException("设备不存在");
        }
        // 检验售货机状态与工单类型是否相同
        checkTaskType(vendingMachine.getVmStatus(), taskDto.getProductTypeId());

        // 检查同类设备是否有未完成的同类型工单
        hasTask(taskDto);

        // 查询员工是否存在
        Emp emp = empService.selectEmpById(taskDto.getUserId());
        if (emp == null) {
            throw new ServiceException("员工不存在");
        }
        // 校验员工区域是否正确
        if (emp.getRegionId().equals(vendingMachine.getRegionId())){
            throw new ServiceException("员工区域不正确");
        }
        // 将DTO转为PO
        Task task = BeanUtil.copyProperties(taskDto, Task.class);
        task.setUpdateTime(DateUtils.getNowDate());
        task.setUserName(emp.getUserName());
        task.setAddr(vendingMachine.getAddr());
        task.setRegionId(vendingMachine.getRegionId());
        task.setTaskStatus(DkdContants.TASK_STATUS_CREATE);
        task.setTaskCode(generateCode());
        int result = taskMapper.insertTask(task);

        // 是否为补货工单
        if (taskDto.getCreateType().equals(DkdContants.TASK_TYPE_SUPPLY)) {
            // 查询工单详情
            List<TaskDetailsDto> details = taskDto.getDetails();
            if (CollUtil.isEmpty(details)) {
                throw new ServiceException("补货工单详情不能为空");
            }
            List<TaskDetails> taskDetailsList = details.stream().map(detail -> {
                TaskDetails taskDetails = BeanUtil.copyProperties(detail, TaskDetails.class);
                taskDetails.setDetailsId(task.getTaskId());
                return taskDetails;
            }).collect(Collectors.toList());
            taskDetailsService.batchInsertTaskDetails(taskDetailsList);
        } else if (taskDto.getCreateType().equals(DkdContants.TASK_TYPE_REVOKE)) { // 是否为退货工单，如果为退货工单则查询该设备是否存在未完成的工单
            Task duplicatedTask = new Task();
            duplicatedTask.setInnerCode(taskDto.getInnerCode());
            List<Task> tasks = taskMapper.selectTaskList(duplicatedTask);
            if (!tasks.isEmpty()){
                throw new ServiceException("该设备存在有未完成的工单！请先完成先前工单或联系管理员");
            }
        }
        return result;
    }

    @Override
    public int cancelTask(Task task) {
        // 判断工单状态是否可以取消
        Task tasktb = taskMapper.selectTaskByTaskId(task.getTaskId());
        if (tasktb.getTaskStatus().equals(DkdContants.TASK_STATUS_CANCEL)) {
            throw new ServiceException("该工单已取消");
        }
        if (tasktb.getTaskStatus().equals(DkdContants.TASK_STATUS_FINISH)) {
            throw new ServiceException("该工单已完成");
        }
        // 设置更新字段
        task.setUpdateTime(DateUtils.getNowDate());
        task.setTaskStatus(DkdContants.TASK_STATUS_CANCEL);
        return taskMapper.updateTask(task);
    }

    private void hasTask(TaskDto taskDto) {
        Task taskParam = new Task();
        taskParam.setInnerCode(taskDto.getInnerCode());
        taskParam.setProductTypeId(taskDto.getProductTypeId());
        taskParam.setTaskStatus(DkdContants.TASK_STATUS_PROGRESS);
        List<Task> tasks = taskMapper.selectTaskList(taskParam);
        if (tasks != null && !tasks.isEmpty()) {
            throw new ServiceException("该设备存在有未完成的同类型工单！");
        }
    }

    private void checkTaskType(Long vmStatus, Long productTypeId) {
        // 投放工单，设备在运行，抛出异常
        // 维修工单，设备不在运营，抛出异常
        // 补货工单，设备不在运营，抛出异常
        // 撤机工单，设备不在运营，抛出异常
        if (productTypeId.equals(DkdContants.TASK_TYPE_DEPLOY) && vmStatus.equals(DkdContants.VM_STATUS_RUNNING)) {
            throw new ServiceException("设备在运行，不能进行投放工单");
        }
        if (productTypeId.equals(DkdContants.TASK_TYPE_REPAIR) && !vmStatus.equals(DkdContants.VM_STATUS_RUNNING)) {
            throw new ServiceException("设备不在运营，不能进行维修工单");
        }
        if (productTypeId.equals(DkdContants.TASK_TYPE_SUPPLY) && !vmStatus.equals(DkdContants.VM_STATUS_RUNNING)) {
            throw new ServiceException("设备不在运营，不能进行补货工单");
        }
        if (productTypeId.equals(DkdContants.TASK_TYPE_REVOKE) && !vmStatus.equals(DkdContants.VM_STATUS_RUNNING)) {
            throw new ServiceException("设备不在运营，不能进行撤机工单");
        }
    }

    // 生成并获取当天的工单编号
    private String generateCode(){
         //获取当前日期年月日"yyyymmdd" 并生成redis的key
        String dateStr = DateUtils.getDate().replaceAll("-","");
        String Key = "dkd.task.code."+ dateStr;
        // 判断是否redis存在该key
        if (!redisTemplate.hasKey(Key)) {
            // 不存在则设置key，并设置过期时间
            redisTemplate.opsForValue().set(Key, 1, Duration.ofDays(1));
            return dateStr+"0001";
        }
        // 如果key存在，则获取当前key对应的value，并自增1
        return dateStr+StrUtil.padPre(redisTemplate.opsForValue().increment(Key).toString(),4,'0');

    }
}
